/*
 * AjaxAuthenticationSuccessHandler.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the org.geek.login.service.impl, Version 1.0 (the "License");
 *
 */
package org.geek.login.service.impl;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.geek.common.base.AppConstants;
import org.geek.domain.User;
import org.geek.login.domain.SecurityUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.WebAuthenticationDetails;

/**
 * <p>登录成功</p>
 * @author ninglong bhd2973@qq.com
 * @version V1.0
 */
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
	
	private Logger logger = LoggerFactory.getLogger(AjaxAuthenticationSuccessHandler.class);
	
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		SecurityUser su = (SecurityUser)authentication.getPrincipal();
		User user = su.getUser();
		request.getSession().setAttribute(AppConstants.LOGINUSER, user);//将用户信息存入session里
		//以下可以记录IP,sessionId
		WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails)authentication.getDetails();
		String remoteAddress = webAuthenticationDetails.getRemoteAddress();
		String sessionId = webAuthenticationDetails.getSessionId();
		if(logger.isDebugEnabled()){
			logger.debug(user.getAccount()+"从网络IP："+remoteAddress+"登录成功,sessionId为："+sessionId);
		}
		 response.setContentType("text/html;charset=UTF-8");
		 PrintWriter out = response.getWriter();
		 out.write("{success:true}");
		 out.close();
	}
}